package com.super8.super8newtv;

import static com.super8.super8newtv.utils.Utils.getStringDate;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stx.xhb.xbanner.XBanner;
import com.super8.super8newtv.adapter.HotelPriceAdapter;
import com.super8.super8newtv.api.Api;
import com.super8.super8newtv.api.ApiContract;
import com.super8.super8newtv.api.ApiError;
import com.super8.super8newtv.api.ApiService;
import com.super8.super8newtv.api.parser.ResponseBeanParser;
import com.super8.super8newtv.api.parser.TokenBeanParser;
import com.super8.super8newtv.bean.HotelpriceBean;
import com.super8.super8newtv.bean.ImagesBean;
import com.super8.super8newtv.bean.MediafileBean;
import com.super8.super8newtv.bean.NoticeBean;
import com.super8.super8newtv.bean.ResponseBean;
import com.super8.super8newtv.bean.TokenBean;
import com.super8.super8newtv.bean.UpdateBean;
import com.super8.super8newtv.bean.WeatherCityBean;
import com.super8.super8newtv.utils.CacheUtil;
import com.super8.super8newtv.utils.DownloadUtil;
import com.super8.super8newtv.utils.FileUtil;
import com.super8.super8newtv.utils.LogUtils;
import com.super8.super8newtv.utils.Utils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;

/**
 * 电子房价牌-竖屏版页面
 */
public class ClockwiseActivity extends AppCompatActivity {
    @BindView(R.id.rl_right)
    RelativeLayout rl_right;//右半屏布局(视频图片)
    //日期 时间
    @BindViews({R.id.tv_now_time, R.id.tv_now_date})
    List<TextView> tvDateTimeList;//日期 时间v相关view
    //天气
    @BindViews({R.id.ll_today_tem_iv, R.id.ll_today_tem})
    List<LinearLayout> llTodayList;//今天天气布局
    @BindViews({R.id.ll_tom_tem_iv, R.id.ll_tom_tem})
    List<LinearLayout> llTomList;//明天天气布局
    @BindViews({R.id.iv_today_weather, R.id.iv_tom_weather})
    List<ImageView> ivWeatherList;//天气图片view
    @BindViews({R.id.tv_today_tem_high, R.id.tv_today_low, R.id.tv_today_weather_type})
    List<TextView> tvTodayTemList;//当天温度 相关view
    @BindViews({R.id.tv_tom_tem_high, R.id.tv_tom_low, R.id.tv_tom_weather_type})
    List<TextView> tvTomTemList;//明天温度 相关view
    @BindView(R.id.recycler_view)
    AutoPollRecyclerView recyclerView;//房价布局
    @BindViews({R.id.tv_hotel_name, R.id.tv_marquee, R.id.tv_hotel_notice})
    List<TextView> tvHotelInfoList;//酒店名称,总部通告, 酒店公告 相关view
    @BindView(R.id.iv_hotel_image)
    ImageView ivHotelImage;//酒店类型图标（1.0 2.0）
    @BindView(R.id.xbanner)
    XBanner mXBanner;//图片
    @BindView(R.id.video_view_right)
    VideoView video_view_right;//半屏_视频

    private List<HotelpriceBean> hotelPriceDataList = new ArrayList<>();
    private List<HotelpriceBean> tempPriceDataList;//
    private HotelPriceAdapter hotelPriceAdapter;


    private List<ImagesBean> imgList;//轮播图片集
    private List<String> imgUrlList;//轮播图片URL集
    private List<String> videoList;//视频集
    int imgesPlayTotal = 0;//图片播放总时长（秒数）
    int imgesPlayNum = 0;//图片播放时长数（秒数）

    List<MediafileBean> lshalfScreenData;
    private int currentPosition = 0;

    private TokenBean tokenBean;//token信息
    List<WeatherCityBean> lsWeather;//城市天气
    private List<NoticeBean> lsNoticeBean;//通知信息

    //全屏广告倒计时
    private String access_token;
    private static final String TAG = "ClockwiseActivity";

    List<String> lsDownFileName;//下载文件信息

    static class HomeHandler extends Handler {
        private final WeakReference<ClockwiseActivity> homeFragmentWeakReference;

        HomeHandler(ClockwiseActivity mainActivity) {
            homeFragmentWeakReference = new WeakReference<ClockwiseActivity>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final ClockwiseActivity activity = homeFragmentWeakReference.get();
            if (activity == null || activity.isFinishing()) {
                removeCallbacksAndMessages(null);
                return;
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private ClockwiseActivity.HomeHandler mHandler = new ClockwiseActivity.HomeHandler(ClockwiseActivity.this) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:  //酒店名称 以及 公告
                    if (!lsNoticeBean.isEmpty()) {
                        //酒店名称
                        tvHotelInfoList.get(0).setText(lsNoticeBean.get(0).getHotelName() + "");//酒店名称
                        //酒店类型
                        if (lsNoticeBean.get(0).getHotelBrand() == 2||lsNoticeBean.get(0).getHotelBrand() == 4)
                            ivHotelImage.setImageResource(R.mipmap.logo_su8_2);
                        else
                            ivHotelImage.setImageResource(R.mipmap.logo_su8_1);
                        String temp = lsNoticeBean.get(0).getNotice();
                        if (temp.length() / 10 < 4) {
                            for (int i = 0; i < 4 - temp.length() / 10; i++)
                                temp += "    " + temp;
                        }
                        tvHotelInfoList.get(1).setText(temp + "");//总部通过
                        //酒店公告
                        if (!TextUtils.isEmpty(lsNoticeBean.get(0).getHotelNotice())) {
                            tvHotelInfoList.get(2).setVisibility(View.VISIBLE);
                            tvHotelInfoList.get(2).setText("酒店公告：" + lsNoticeBean.get(0).getHotelNotice());
                        } else {
                            tvHotelInfoList.get(2).setVisibility(View.GONE); //隐藏酒店公告
                        }
                    }
                    break;
                case 2: //房价
                    hotelPriceDataList.clear();
                    hotelPriceDataList.addAll(tempPriceDataList);
                    if (tempPriceDataList.size() > 6)
                        hotelPriceAdapter.setDataNum(10);
                    else
                        hotelPriceAdapter.setDataNum(1);
                    hotelPriceAdapter.notifyDataSetChanged();
                    recyclerView.start();//开始循环滚动
                    break;
                case 3:  //半屏数据获取
                    String mediafiles = msg.getData().getString("mediafiles");
                    List<MediafileBean> ls = new Gson().fromJson(mediafiles, new TypeToken<List<MediafileBean>>() {
                    }.getType());
                    if (ls != null && ls.size() > 0) {
                        lshalfScreenData = ls;
                        showHalfScreenData(); //展示半屏
                    }
                    break;
                case 30:
                    showHalfScreenData();//半屏展示
                    break;
                case 5://图片转换到视频播放
                    loadBanner(imgList, imgUrlList);
                    break;
                case 6:  //实时更新数据
                    String updateData = msg.getData().getString("updateData");
                    UpdateBean updateBean = new Gson().fromJson(updateData, UpdateBean.class);
                    if (updateBean != null) {
                        int notice = updateBean.getNotice();
                        int halfScreen = updateBean.getHalfScreen();
                        int prices = updateBean.getPrices();
                        getWeather();
                        if (notice == 1)
                            getNotices();//获取滚动字幕
                        if (halfScreen == 1)
                            getMediafiles();  //获取半屏广告
                        if (prices == 1)
                            getHotelprice();  //获取酒店房型以及价钱
                    }
                    break;
                case 500:  //当前时间更新
                    String substring = getStringDate().substring(11, 16);
                    tvDateTimeList.get(0).setText(substring + "");
                    break;
                case 501://当前日期 星期更新
                    String nowTime = Utils.getNowTime();
                    String currentWeek = Utils.dateToWeek(nowTime);
                    String month = Utils.getNowTime().substring(5, 7);
                    String day = Utils.getNowTime().substring(8, 10);
                    tvDateTimeList.get(1).setText(month + "月" + day + "日  " + currentWeek);//日期
                    break;
                case 8://获取天气(crs系统中)
                    LogUtils.e("GetWeather", "lsWeather：" + new Gson().toJson(lsWeather));
                    setWeather(lsWeather.get(0).getWeather(), ivWeatherList.get(0));
                    tvTodayTemList.get(0).setText(lsWeather.get(0).getTemEnd() + "°");//当天最高
                    tvTodayTemList.get(1).setText(lsWeather.get(0).getTemStart() + "°");//当天最低
                    tvTodayTemList.get(2).setText(lsWeather.get(0).getWeather() + "");//当天天气
                    if (lsWeather.size() > 1) {
                        llTomList.get(0).setVisibility(View.VISIBLE);
                        llTomList.get(1).setVisibility(View.VISIBLE);
                        setWeather(lsWeather.get(1).getWeather(), ivWeatherList.get(1));
                        tvTomTemList.get(0).setText(lsWeather.get(1).getTemEnd() + "°");//明天最高
                        tvTomTemList.get(1).setText(lsWeather.get(1).getTemStart() + "°");//明天最低
                        tvTomTemList.get(2).setText(lsWeather.get(1).getWeather() + "");//明天天气
                    } else {
                        llTomList.get(0).setVisibility(View.GONE);
                        llTomList.get(1).setVisibility(View.GONE);
                    }
                    break;
                case -8:
                    llTodayList.get(0).setVisibility(View.GONE);
                    llTodayList.get(1).setVisibility(View.GONE);
                    llTomList.get(0).setVisibility(View.GONE);
                    llTomList.get(1).setVisibility(View.GONE);
                    break;
                case 20:
                    recyclerView.smoothScrollToPosition(0);
                    break;
                case 110:
                    autoLogon();//重新自动登录
                    break;
                case 120:
                    //登录失败
                    Toast.makeText(ClockwiseActivity.this, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(ClockwiseActivity.this, MainActivity.class));//跳转登录页面
                    break;
            }
        }
    };


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clockwise);
        ButterKnife.bind(this);
        checkToken();//检测token
        initView();
        initData();
        initRunnable();//
    }

    /**
     * 初始化控件
     */
    private void initView() {
        Intent intent = getIntent();
        String nowTime = Utils.getNowTime();
        String currentWeek = Utils.dateToWeek(nowTime);
        String month = Utils.getNowTime().substring(5, 7);
        String day = Utils.getNowTime().substring(8, 10);
        tvDateTimeList.get(1).setText(month + "月" + day + "日  " + currentWeek);//日期
        String substring = getStringDate().substring(11, 16);
        tvDateTimeList.get(0).setText(substring + "");//时间

        //跑马灯效果必须加
        tvHotelInfoList.get(1).setSelected(true);//总部通告
        tvHotelInfoList.get(2).setSelected(true);//酒店通告

        String direction = intent.getStringExtra("direction");
        if (!TextUtils.isEmpty(direction)) {
            if (direction.equals("clockwise")) {  //顺时针
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            } else {  //逆时针
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
            }
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        hotelPriceDataList = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(ClockwiseActivity.this));
        hotelPriceAdapter = new HotelPriceAdapter(ClockwiseActivity.this, hotelPriceDataList);
        hotelPriceAdapter.setOnItemClickListener(new HotelPriceAdapter.OnLastItemLister() {
            @Override
            public void onLastItem() {
//                handler.postDelayed(rblHotelPriceData, 1000);//追加房价循环播放数据
//                recyclerView.smoothScrollToPosition(0);
//                ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0,0);
                mHandler.sendEmptyMessage(20);
            }
        });
        recyclerView.setAdapter(hotelPriceAdapter);
        imgList = new ArrayList<>();
        imgUrlList = new ArrayList<>();
        videoList = new ArrayList<>();
        lsDownFileName = new ArrayList<>();
        imgesPlayTotal = 0;
        imgesPlayNum = 0;
        lshalfScreenData = new ArrayList<>();
        if (!TextUtils.isEmpty(access_token)) {
            getNotices(); //获取公告语 滚动字幕
            getHotelprice(); //获取酒店房型以及价钱
            getMediafiles();  //获取半屏广告
            getWeather();  //获取天气
        }
    }

    //初始酒店房价信息
    Runnable rblHotelPriceData = new Runnable() {
        public void run() {
            if (hotelPriceDataList.size() > 100) {
                hotelPriceDataList.clear();
                hotelPriceDataList.addAll(tempPriceDataList);
            }
            if (tempPriceDataList.size() > 7) {
                hotelPriceDataList.addAll(tempPriceDataList);
            }

            hotelPriceAdapter.setDataNum(50);
            hotelPriceAdapter.notifyDataSetChanged();
            if (hotelPriceDataList != null && hotelPriceDataList.size() > 7)
                if (!recyclerView.isRunning())
                    recyclerView.start();//开始循环滚动
        }
    };

    /**
     * 初始计时器
     */
    private void initRunnable() {
        runnable = new Runnable() {
            public void run() {
                handler.postDelayed(this, 1000);//延迟1秒钟
                //获取当前时间
                Date dateNow = new Date(System.currentTimeMillis());
                int h = dateNow.getHours();
                int m = dateNow.getMinutes();
                int s = dateNow.getSeconds();
                if (s % 10 == 0)
                    checkToken();//检查token
                if (h == 0 && m == 0 && s == 1)
                    mHandler.sendEmptyMessage(501);//设置日期 星期 显示
                if (s == 0)
                    mHandler.sendEmptyMessage(500);//设置分钟显示

                if (h % 1 == 0 && m == 0 && s == 10)//每1小时 刷新天气
                    getWeather();

                if (m % 5 == 0 && s == 2)
                    getDataUpdate();  //心跳包  五分钟刷新一次数据

                if (s % 5 == 0 && !recyclerView.canScrollVertically(1)) {
                    //判断 是否滑倒底部
                    if (!recyclerView.canScrollVertically(1)) {
                        mHandler.sendEmptyMessage(20);
                    }
                }
            }
        };
        handler.postDelayed(runnable, 1000); // 开始Timer
    }

    //半屏展示
    private void showHalfScreenData() {
        if (lshalfScreenData != null && lshalfScreenData.size() > 0) {
            imgList.clear();
            imgUrlList.clear();
            videoList.clear();
            lsDownFileName.clear();
            String tempUrl;
            String printTxtPath = getApplicationContext().getFilesDir().getAbsolutePath();
            for (int i = 0; i < lshalfScreenData.size(); i++) {
                tempUrl = lshalfScreenData.get(i).getFileUrl() + "";
                if (!tempUrl.endsWith(".mp4")) {  //图片
                    imgList.add(new ImagesBean(tempUrl));
                    imgUrlList.add(tempUrl);
                } else {
                    videoList.add(tempUrl);
                    //判断视频信息
                    String downFielName = DownloadUtil.getUrlLastNameSuffix(tempUrl);
                    if (!FileUtil.isFileExist(printTxtPath + "/" + downFielName)) {//文件是否存在
                        String finalTempUrl = tempUrl;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                downFile(finalTempUrl, printTxtPath, downFielName); //下载
                            }
                        }).start();
                    } else {
                        lsDownFileName.add(downFielName);//已存在
                    }
                }
            }
            //加载 轮播图或视频
            showBannerOrVideo(imgList, imgUrlList);
        }
    }

    /*@
     * 文件下载 url：地址 filepateh： 存放文件路径  filename: 文件名字
     */
    private void downFile(String url, String filepath, String filename) {
        DownloadUtil.get().download(url, filepath, filename,
                new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        if (!lsDownFileName.contains(filename))
                            lsDownFileName.add(filename);
                        //下载成功
                        LogUtils.i(TAG, "onDownloadSuccess:....... ..................文件下载成功..............................");
                    }

                    @Override
                    public void onDownloading(int progress) {
                        //下载中
                        LogUtils.i(TAG, "onDownloading:..............................文件下载中................................");
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        //下载异常进行相关提示操作
                        LogUtils.e(TAG, "onDownloadFailed:..........................下载文件失败..............................." + e.getMessage());
                    }
                });
    }

    /**
     * 显示 轮播图 或视频
     *
     * @param lsImg 轮播图
     * @param lsUrl 轮播图Url
     */
    private void showBannerOrVideo(final List<ImagesBean> lsImg, final List<String> lsUrl) {
        if (imgList != null && imgList.size() > 0) {
            loadBanner(lsImg, lsUrl);
        } else {
            loadVideo(lsImg, lsUrl);
        }
    }

    /**
     * 加载 播放轮播图 imgUrlList
     */
    private void loadBanner(final List<ImagesBean> lsImg, final List<String> lsUrl) {
        if ((lsImg == null || lsImg.size() == 0) && (lsDownFileName == null || lsDownFileName.size() == 0))
            return;
        if (lsImg != null && lsImg.size() > 0) {
            mXBanner.setVisibility(View.VISIBLE);
            video_view_right.setVisibility(View.GONE);
            //加载广告图片
            mXBanner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object model, View view, int position) {
                    SimpleDraweeView draweeView = (SimpleDraweeView) view;
                    draweeView.setImageURI(Uri.parse(lsUrl.get(position)));
                    draweeView.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
                }
            });
            final int[] index = {0};
            //轮播图 滚动 监听事件
            mXBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }

                @Override
                public void onPageSelected(int position) {

                }

                @Override
                public void onPageScrollStateChanged(int state) {
                    if (state == 2) {  //当滑动完毕的时候
                        index[0] = index[0] + 1;
                        if (index[0] > lsUrl.size()) {
                            if (lsImg == null || lsImg.size() <= 0) {
                                mHandler.sendEmptyMessage(30);//切换半屏显示
                            } else {
                                loadVideo(lsImg, lsUrl);//直接跳转视频播放
                            }
                        }
                    }
                }
            });

            //添加轮播图片数据
            mXBanner.setBannerData(R.layout.layout_fresco_homebanner, lsImg);
        } else {
            loadVideo(lsImg, lsUrl);//直接跳转视频播放
        }
    }

    /**
     * 加载 播放视频
     */
    private void loadVideo(final List<ImagesBean> lsImg, final List<String> lsUrl) {
        if (lsDownFileName != null && lsDownFileName.size() > 0) {
            //设置播放视频
            String absolutePath = getApplicationContext().getFilesDir().getAbsolutePath() + "/";  //"/halftest.mp4";
            //播放视频  半屏
            mXBanner.setVisibility(View.GONE);
            video_view_right.setVisibility(View.VISIBLE);
            currentPosition = 0;
            //监听视频资源装载完成
            video_view_right.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    video_view_right.start();//开始播放视频
                }
            });
            //监听视频播放完成
            video_view_right.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    video_view_right.stopPlayback();
                    currentPosition++;
                    //判断视频数量
                    if (currentPosition <= lsDownFileName.size() - 1) {
                        try {
                            //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径3" + uri);
                            String uri = absolutePath + lsDownFileName.get(currentPosition);
                            if (!TextUtils.isEmpty(uri)) {
                                video_view_right.setVideoURI(Uri.parse(uri));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (lsImg != null && lsImg.size() > 0)
                            loadBanner(imgList, lsUrl);//播放图片
                    }
                }
            });
            //监听视频播放出错
            video_view_right.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    stopPlaybackVideo();
                    //当前视频播放异常 播放下个
                    currentPosition++;
                    //判断视频数量
                    if (currentPosition <= lsDownFileName.size() - 1) {
                        try {
                            //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径3" + uri);
                            String uri = absolutePath + lsDownFileName.get(currentPosition);
                            if (!TextUtils.isEmpty(uri)) {
                                video_view_right.setVideoURI(Uri.parse(uri));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (lsImg != null && lsImg.size() > 0)
                            loadBanner(imgList, lsUrl);//播放图片
                    }
                    return true;
                }
            });

            try {
                video_view_right.stopPlayback();
                //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径4" + uri);
                String uri = absolutePath + lsDownFileName.get(currentPosition);
                if (!TextUtils.isEmpty(uri)) {
                    video_view_right.setVideoURI(Uri.parse(uri));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (lsImg != null && lsImg.size() > 0)
                loadBanner(lsImg, lsUrl);//播放图片   没有视频直接播放图片
        }
    }

    private Runnable runnable;
    private Handler handler = new Handler();

    /**
     * 检查token是否过期
     */
    public boolean checkToken() {
        boolean rs = false;
        tokenBean = CacheUtil.getTokenCache(this);
        if (tokenBean != null && tokenBean.isNoExpire()) {
            access_token = tokenBean.getAccess_token();
            rs = true;
        } else {
            //刷新token
            String refreshToken = CacheUtil.getCache(this).getString("RefreshToken");
            if (!TextUtils.isEmpty(refreshToken))
                refreshToken(tokenBean.getRefresh_token());//刷新可用  刷新token
            else
                autoLogon();//重新登录
        }
        return rs;
    }

    /**
     * 刷新token
     */
    private void refreshToken(String refresh_token) {
        HashMap<String, String> refreshMap = new HashMap<>();
        refreshMap.put("grant_type", "refresh_token");
        refreshMap.put("refresh_token", refresh_token);
        TokenBeanParser<TokenBean> responseBeanParser = new TokenBeanParser<TokenBean>(new TypeToken<TokenBean>() {
        }.getType());
        ApiService.getInstance().get(Api.ACCESS_TOKEN, refreshMap, responseBeanParser, new ApiContract.OnResponseListener<TokenBean>() {
            @Override
            public void onSuccess(ResponseBean<TokenBean> result) {
                if (result.isSuccess()) {//登录成功
                    CacheUtil.setTokenCache(ClockwiseActivity.this, result.getData());//保存token
                    tokenBean=result.getData();
                    access_token = tokenBean.getAccess_token();
                } else {
                    //刷新token失败
                    Message message = Message.obtain();
                    message.what = 110;
                    mHandler.sendMessage(message);
                }
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
                LogUtils.e("refreshToken ", "刷新token异常 onError:" + error.getErrorMessage());
                //发送数据
                Message message = Message.obtain();
                message.what = 110;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 重新获取登录token
     */
    private void autoLogon() {
        String client_id = CacheUtil.getCache(ClockwiseActivity.this).getString("client_id", "");
        String client_secret = CacheUtil.getCache(ClockwiseActivity.this).getString("client_secret", "");
        String versionName = Utils.getVersionName(ClockwiseActivity.this);
        String deviceId = Utils.getDeviceId(ClockwiseActivity.this);
        String currentapiVersion = "android_" + Build.VERSION.RELEASE;
        HashMap<String, String> reqMap = new HashMap<>();
        reqMap.put("device_id", deviceId);
        reqMap.put("os_version", currentapiVersion);
        reqMap.put("version", versionName);
        reqMap.put("grant_type", "client_credentials");
        reqMap.put("client_id", client_id);
        reqMap.put("client_secret", client_secret);
        reqMap.put("screentype", "V");
        TokenBeanParser<TokenBean> responseBeanParser = new TokenBeanParser<TokenBean>(new TypeToken<TokenBean>() {
        }.getType());
        ApiService.getInstance().get(Api.ACCESS_TOKEN, reqMap, responseBeanParser, new ApiContract.OnResponseListener<TokenBean>() {
            @Override
            public void onSuccess(ResponseBean<TokenBean> result) {
                if (result.isSuccess()) {//登录成功
                    CacheUtil.setTokenCache(ClockwiseActivity.this, result.getData());//保存token
                    CacheUtil.getCache(ClockwiseActivity.this).put("client_id", client_id);
                    CacheUtil.getCache(ClockwiseActivity.this).put("client_secret", client_secret);
                    tokenBean=result.getData();
                    access_token = tokenBean.getAccess_token();
                } else {
                    //发送数据
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", "登录身份失效!" + result.getError_description());
                    Message message = Message.obtain();
                    message.setData(bundle);   //message.obj=bundle  传值也行
                    message.what = 120;
                    mHandler.sendMessage(message);
                }
            }

            @Override   //登录失败
            public void onError(ApiError error) {
//                CacheUtil.getCache(ClockwiseActivity.this).remove("client_id");
//                CacheUtil.getCache(ClockwiseActivity.this).remove("client_secret");
                LogUtils.e("getLoginToken ", "onError:" + error.getErrorMessage());
                //发送数据
                Bundle bundle = new Bundle();
                bundle.putString("msg", "登录身份异常!" + error.getErrorMessage());
                Message message = Message.obtain();
                message.setData(bundle);   //message.obj=bundle  传值也行
                message.what = 120;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 实时刷新数据
     */
    private void getDataUpdate() {
        ResponseBeanParser<UpdateBean> responseBeanParser = new ResponseBeanParser<UpdateBean>(new TypeToken<ResponseBean<UpdateBean>>() {
        }.getType());
        ApiService.getInstance().get(
                Api.Update_Data, access_token, responseBeanParser,
                new ApiContract.OnResponseListener<UpdateBean>() {
                    @Override
                    public void onSuccess(ResponseBean<UpdateBean> result) {
                        if (result != null && result.isSuccess() && result.getData() != null) {
                            String str = new Gson().toJson(result.getData());
                            //传递的数据
                            Bundle bundle = new Bundle();
                            bundle.putString("updateData", str);
                            //发送数据
                            Message message = Message.obtain();
                            message.setData(bundle);   //message.obj=bundle  传值也行
                            message.what = 6;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onError(ApiError error) {
                    }
                });
    }

    /**
     * 获取公告语
     */
    private void getNotices() {
        ResponseBeanParser<List<NoticeBean>> responseBeanParser = new ResponseBeanParser<List<NoticeBean>>(new TypeToken<ResponseBean<List<NoticeBean>>>() {
        }.getType());
        ApiService.getInstance().get(Api.Notices, access_token, responseBeanParser, new ApiContract.OnResponseListener<List<NoticeBean>>() {
            @Override
            public void onSuccess(ResponseBean<List<NoticeBean>> result) {
                if (result.isSuccess()) {//获取成功
                    if (!result.getData().isEmpty()) {
                        lsNoticeBean = result.getData();
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                }
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
                LogUtils.e("getNotices ", "获取公告语 onError:" + error.getErrorMessage());
            }
        });
    }

    /**
     * 获取酒店房价
     */
    private void getHotelprice() {
        ResponseBeanParser<List<HotelpriceBean>> responseBeanParser = new ResponseBeanParser<List<HotelpriceBean>>(new TypeToken<ResponseBean<List<HotelpriceBean>>>() {
        }.getType());
        ApiService.getInstance().get(Api.Hotel_Prices, access_token, responseBeanParser, new ApiContract.OnResponseListener<List<HotelpriceBean>>() {
            @Override
            public void onSuccess(ResponseBean<List<HotelpriceBean>> result) {
                if (result.isSuccess()) {//获取成功
                    if (result.getData() != null) {
                        tempPriceDataList = result.getData();
                        Message message = Message.obtain();
                        message.what = 2;
                        mHandler.sendMessage(message);
                    }
                }
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
            }
        });
    }

    /**
     * 获取天气预报  .url("https://tianqiapi.com/api?version=v1&appid=32929963&appsecret=38JNKHHL")
     */
    private void getWeather() {
        ResponseBeanParser<List<WeatherCityBean>> responseBeanParser = new ResponseBeanParser<List<WeatherCityBean>>(new TypeToken<ResponseBean<List<WeatherCityBean>>>() {
        }.getType());
        ApiService.getInstance().get(Api.Weather, access_token, responseBeanParser, new ApiContract.OnResponseListener<List<WeatherCityBean>>() {
            @Override
            public void onSuccess(ResponseBean<List<WeatherCityBean>> result) {
                Message message = Message.obtain();
                if (result.isSuccess() && !result.getData().isEmpty()) {//获取天气预报成功
                    lsWeather = result.getData();
                    message.what = 8;
                } else {
                    message.what = -8;
                }
                mHandler.sendMessage(message);   //发送数据
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
                LogUtils.e("GetWeather ", "获取天气异常 onError:" + error.getErrorMessage());
                Message message = Message.obtain();
                message.what = -8;
                mHandler.sendMessage(message);   //发送数据
            }
        });
    }

    /**
     * 设置天气 图片
     */
    private void setWeather(String weather, ImageView ivTemp) {
        if (weather.contains("晴")) {
            ivTemp.setImageResource(R.mipmap.sun);
        } else if (weather.contains("多云")) {
            ivTemp.setImageResource(R.mipmap.duoyun);
        } else if (weather.contains("阴")) {
            ivTemp.setImageResource(R.mipmap.yin);
        } else if (weather.contains("小雨")) {
            ivTemp.setImageResource(R.mipmap.xiaoyu);
        } else if (weather.contains("中雨")) {
            ivTemp.setImageResource(R.mipmap.zhongyu);
        } else if (weather.contains("雷阵雨")) {
            ivTemp.setImageResource(R.mipmap.leizhenyu);
        } else if (weather.contains("阵雨")) {
            ivTemp.setImageResource(R.mipmap.zhenyu);
        } else if (weather.contains("大雨")) {
            ivTemp.setImageResource(R.mipmap.dayu);
        } else if (weather.contains("暴雨")) {
            ivTemp.setImageResource(R.mipmap.baoyu);
        } else if (weather.contains("大暴雨")) {
            ivTemp.setImageResource(R.mipmap.dabaoyu);
        } else if (weather.contains("冻雨")) {
            ivTemp.setImageResource(R.mipmap.dongyu);
        } else if (weather.contains("雾")) {
            ivTemp.setImageResource(R.mipmap.wu);
        } else if (weather.contains("轻雾")) {
            ivTemp.setImageResource(R.mipmap.qingwu);
        } else if (weather.contains("霾")) {
            ivTemp.setImageResource(R.mipmap.mai);
        } else if (weather.contains("冰雹")) {
            ivTemp.setImageResource(R.mipmap.bingbao);
        } else if (weather.contains("浮尘")) {
            ivTemp.setImageResource(R.mipmap.fuchen);
        } else if (weather.contains("沙尘暴")) {
            ivTemp.setImageResource(R.mipmap.shachenbao);
        } else if (weather.contains("扬沙")) {
            ivTemp.setImageResource(R.mipmap.yangsha);
        } else if (weather.contains("小雪")) {
            ivTemp.setImageResource(R.mipmap.xiaoyu);
        } else if (weather.contains("中雪")) {
            ivTemp.setImageResource(R.mipmap.zhongxue);
        } else if (weather.contains("大雪")) {
            ivTemp.setImageResource(R.mipmap.daxue);
        } else if (weather.contains("阵雪")) {
            ivTemp.setImageResource(R.mipmap.zhenxue);
        } else if (weather.contains("雨夹雪")) {
            ivTemp.setImageResource(R.mipmap.yujiaxue);
        } else if (weather.contains("暴雪")) {
            ivTemp.setImageResource(R.mipmap.baoxue);
        }
    }

    /**
     * 获取酒店  图片 和  视频(半屏) 数据获取
     */
    private void getMediafiles() {
        ResponseBeanParser<List<MediafileBean>> responseBeanParser = new ResponseBeanParser<List<MediafileBean>>(new TypeToken<ResponseBean<List<MediafileBean>>>() {
        }.getType());
        ApiService.getInstance().get(
                Api.Media_Files, access_token, responseBeanParser,
                new ApiContract.OnResponseListener<List<MediafileBean>>() {
                    @Override
                    public void onSuccess(ResponseBean<List<MediafileBean>> result) {
                        if (result != null && result.isSuccess() && result.getData() != null && result.getData().size() > 0) {
                            //传递的数据
                            Bundle bundle = new Bundle();
                            bundle.putString("mediafiles", new Gson().toJson(result.getData()));
                            //发送数据
                            Message message = Message.obtain();
                            message.setData(bundle);   //message.obj=bundle  传值也行
                            message.what = 3;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onError(ApiError error) {
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!video_view_right.isPlaying())
            video_view_right.resume();//将视频从头开始播放
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (video_view_right.canPause())
            video_view_right.pause();//暂停播放视频
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlaybackVideo();
        handler.removeCallbacks(runnable); //停止Timer
        handler.removeCallbacksAndMessages(null);
        mHandler.removeCallbacksAndMessages(null);
    }

    /**
     * 停止视频播放
     */
    private void stopPlaybackVideo() {
        try {
            video_view_right.stopPlayback();  //loadBanner(imgList, imgUrlList, videoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
